package com.hunttown.mes.manage.controller._basic;

import com.hunttown.mes.common.OperateCode;
import com.hunttown.mes.rpc.domain.AnalysisVisualCatalogDTO;
import com.hunttown.mes.rpc.domain.WorkflowBusinessDTO;
import com.hunttown.mes.rpc.domain.query.WorkflowBusinessDTOQuery;
import com.hunttown.common.domain.Page;
import com.hunttown.mes.manage.controller.common.AdminBaseClass;
import com.hunttown.mes.manage.controller.common.ModelService;
import com.hunttown.mes.rpc.domain.AnalysisManageDTO;
import com.hunttown.mes.rpc.domain.WorkflowApplyDTO;
import com.hunttown.mes.rpc.domain.enums.workflow.ApplyStatusEnum;
import com.hunttown.mes.rpc.domain.query.WorkflowApplyDTOQuery;
import com.hunttown.mes.common.utils.*;
import com.hunttown.mes.manage.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

import java.util.*;

import static com.hunttown.mes.common.utils.PageUtils.PagePackage;

/**
 * @title: 流程审批列表
 * @author: wangjunfu
 * @date: 2019-08-01 16:55:14
 * @description:
 */
@Controller
@RequestMapping(value = "/basic/wfapply")
public class WFApplyController {

    private final static Logger logger = LoggerFactory.getLogger(WFApplyController.class);

    private final AnalysisManageManageService manageService;
    private final AnalysisCatalogManageService catalogService;
    private final TransactionService transactionService;
    private final TransportOperateLogManageService logService;
    private final WorkflowApplyManageService applyService;
    private final WorkflowBusinessManageService businessService;
    private final ModelService modelService;

    @Autowired
    public WFApplyController(WorkflowApplyManageService applyService, AnalysisManageManageService manageService, AnalysisCatalogManageService catalogService, WorkflowBusinessManageService businessService, ModelService modelService, TransactionService transactionService, TransportOperateLogManageService logService) {
        this.applyService = applyService;
        this.manageService = manageService;
        this.catalogService = catalogService;
        this.businessService = businessService;
        this.modelService = modelService;
        this.transactionService = transactionService;
        this.logService = logService;
    }

    //region 数据列表

    /**
     * 首页
     *
     * @param model    model模型
     * @param dtoQuery 查询条件
     * @return vm
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(HttpServletRequest request, Model model, WorkflowApplyDTOQuery dtoQuery) {

        //region 多选初始化
        if (dtoQuery.getShowRecall() == null) {
            dtoQuery.setShowRecall(0);
        }
        if (dtoQuery.getShowReject() == null) {
            dtoQuery.setShowReject(0);
        }
        if (dtoQuery.getShowCancle() == null) {
            dtoQuery.setShowCancle(0);
        }
        if (dtoQuery.getOnlySearchSelf() == null) {
            dtoQuery.setOnlySearchSelf(0);
        }
        //endregion

        //查询日期（初始化 30天）
        if (StringUtils.isBlank(dtoQuery.getDaterange())) {
            dtoQuery.setDaterange(String.format("%s ~ %s", DateConvertUtils.getPastDate(30), DateConvertUtils.getPastDate(0)));
        }

        if (StringUtils.isNotBlank(dtoQuery.getDaterange())) {
            String[] date = dtoQuery.getDaterange().split("~");
            if (date.length == 2) {
                model.addAttribute("startDate", date[0].trim());
                model.addAttribute("endDate", date[1].trim());
            }
        }

        //流程
        AnalysisVisualCatalogDTO catalogDTO = catalogService.getByCateEnName("shenpiliucheng");

        WorkflowBusinessDTOQuery query = new WorkflowBusinessDTOQuery();
        if (dtoQuery.getApplyType() != null && dtoQuery.getApplyType() == 1) { //普通审批
            query.setCatalogId(catalogDTO == null ? 0 : catalogDTO.getId());
            query.setBusinessType(1);
        }
        query.setPageSize(50);
        query.setStopFlag(0);
        Page<WorkflowBusinessDTO> businessPage = businessService.getForPage(query);

        model.addAttribute("businessPage", businessPage);
        model.addAttribute("cateId", 0);

        //审批状态
        model.addAttribute("applyStatusList", ApplyStatusEnum.getEnumList());

        model.addAttribute("dtoQuery", dtoQuery);
        return "basic/wfapply/index";
    }

    @RequestMapping(value = "/getApplyList", method = RequestMethod.POST)
    public String ajaxGetApplyList(HttpServletRequest request, Model model, WorkflowApplyDTOQuery dtoQuery) {

        //region 多选初始化
        if (dtoQuery.getShowRecall() == null) {
            dtoQuery.setShowRecall(0);
        }
        if (dtoQuery.getShowReject() == null) {
            dtoQuery.setShowReject(0);
        }
        if (dtoQuery.getShowCancle() == null) {
            dtoQuery.setShowCancle(0);
        }
        if (dtoQuery.getOnlySearchSelf() == null) {
            dtoQuery.setOnlySearchSelf(0);
        }
        //endregion

        //管理ID转换为USERID
        String pin = AdminBaseClass.getPin(request);
        AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
        Integer myId = modelService.getUserIdByAdminId(curr_obj.getId());

        Page<WorkflowApplyDTO> dataPage;

        //查询日期（初始化 30天）
        if (StringUtils.isBlank(dtoQuery.getDaterange())) {
            dtoQuery.setDaterange(String.format("%s ~ %s", DateConvertUtils.getPastDate(30), DateConvertUtils.getPastDate(0)));
        }

        //【01】、从首页过来的，只查询与自己相关的（首页会传过来一堆ID）
        if (dtoQuery.getFromIndex() != null && dtoQuery.getFromIndex() == 1) {
            myId = modelService.getUserIdByAdminId(dtoQuery.getSecondaryCurrUser());
            dtoQuery.setSecondaryCurrUser(myId);

            dtoQuery.setOrderBy("order by a.id desc");
            dataPage = applyService.getJoinSecondaryForPage(dtoQuery);

        } else {
            //【02】、查看全部数据（管理员，拥有权限的人）
            Integer canExec = modelService.getLookAlldataAuthor(pin);
            if (dtoQuery.getOnlySearchSelf() == 0 && canExec > 0) {
                dtoQuery.setOrderBy("order by id desc");
                dataPage = applyService.getForPage(dtoQuery);

            } else {
                //【03】、正常访问（只查看自己的）
                //审批的状态：-10撤回 -1驳回 0审批中 1已完成
                List<Integer> statuList = new ArrayList<>();
                statuList.add(0);
                statuList.add(1);
                dtoQuery.setStatuList(statuList);

                dtoQuery.setApplyLikeName(dtoQuery.getLikeName());
                dtoQuery.setSecondaryCurrUser(myId);
                dtoQuery.setStopFlag(0);
                dtoQuery.setOrderBy("order by a.id desc");
                dataPage = applyService.getJoinSecondaryForPage(dtoQuery);
            }

        }

        // 实时更新列表信息
        if (dataPage != null && dataPage.getItems().size() > 0) {
            WorkflowBusinessDTO businessDTO;

            for (WorkflowApplyDTO item : dataPage.getItems()) {
                //申请人
                item.setApplyName(modelService.getManageName(item.getApply()));

                //审批状态
                item.setStatusName(ApplyStatusEnum.getEnumByKey(item.getStatus()));

                //流程类型
                businessDTO = businessService.getById(item.getBusinessId());
                item.setBusinessName(businessDTO == null ? "--" : businessDTO.getBusinessName());
            }
        }

        model.addAttribute("page", dataPage);
        model.addAttribute("PagePackage", PagePackage(dataPage.getPn(), dataPage.getStart(), dataPage.getPageSize(), dataPage.getTotalPages(), dataPage.getTotalItems()));
        model.addAttribute("dtoQuery", dtoQuery);

        // 类别
        if (dtoQuery.getBusinessId() == null) {
            model.addAttribute("cateId", 0);
        } else {
            model.addAttribute("cateId", dtoQuery.getBusinessId());
        }

        return "basic/wfapply/com-content";
    }
    //endregion

    //region 编辑&保存

    /**
     * 编辑
     *
     * @param model model模型
     * @param id    主键id
     * @return vm
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(HttpServletRequest request, Model model, Integer id) {
        id = (id == null ? 0 : id);

        String pin = AdminBaseClass.getPin(request);
        AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);

        WorkflowApplyDTO obj = new WorkflowApplyDTO();
        obj.setId(id);
        obj.setApplyType(1);

        obj.setApply(curr_obj.getId());
        obj.setReviewer(0);

        obj.setApplyTitle(String.format("%s%s的（）申请", curr_obj.getNickName(), DateConvertUtils.dateToShortStr(new Date())));

        if (id > 0) {
            obj = applyService.getById(id);
        }
        model.addAttribute("Obj", obj);

        AnalysisVisualCatalogDTO catalogDTO = catalogService.getByCateEnName("shenpiliucheng");

        WorkflowBusinessDTOQuery query = new WorkflowBusinessDTOQuery();
        query.setCatalogId(catalogDTO == null ? 0 : catalogDTO.getId());
        query.setBusinessType(3); //通用审批
        query.setStopFlag(0);
        Page<WorkflowBusinessDTO> flowPage = businessService.getForPage(query);
        model.addAttribute("flowPage", flowPage);

        modelService.getManagerPage(model);

        return "basic/wfapply/edit";
    }

    /**
     * 保存 ajax异步
     *
     * @param request sevelet请求
     * @param objDTO  实体类
     * @return json
     */
    @RequestMapping(value = "/saveEdit", method = RequestMethod.POST)
    @ResponseBody
    public String saveEditNotify(HttpServletRequest request, WorkflowApplyDTO objDTO) {

        // 结果返回 结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        try {
            String pin = AdminBaseClass.getPin(request);
            AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);

            if (objDTO.getId() == null || objDTO.getId() <= 0) {

                //region STEP 01 新增
                objDTO.setAdminId(curr_obj.getId());
                objDTO.setCreateTime(new Date());
                objDTO.setStopFlag(0);
                objDTO.setDeleteFlag(0);

                objDTO.setReviewTime(new Date());
                objDTO.setApplyType(1); //日常审批
                objDTO.setApplyTime(new Date());
                objDTO.setTableId(82);
                objDTO.setRecordId(0);
                objDTO.setStatus(0);

                objDTO = applyService.insert(objDTO);

                if (objDTO == null || objDTO.getId() <= 0) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }
                //endregion

                //region STEP 02 生成审批流程

                //[改版后]审批人走的是会员系统
                Map<String, String> param = new HashMap<>();
                param.put("firstExector", modelService.getUserIdByAdminId(objDTO.getApply()) + "");
                param.put("secondExector", modelService.getUserIdByAdminId(objDTO.getReviewer()) + "");

                transactionService.insertWfLine(objDTO.getBusinessId(), objDTO.getId(), objDTO.getAdminId(), param);

                //endregion

            } else {
                //更新
                //将不需要更新的字段设置为NULL
                Boolean isNext = applyService.updateInfoById(objDTO);

                if (isNext) {
                    //设置第一审批人和每2审批人
                    if (objDTO.getId() > 0) {
                        Map<Integer, Integer> replaceMap = new HashMap<>();
                        replaceMap.put(1, objDTO.getApply());
                        replaceMap.put(2, objDTO.getReviewer());
                        transactionService.setExector(objDTO.getId(), replaceMap);
                    }
                } else {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }
            }

            //region *** 更新信息完毕记录操作日志 ***
            logService.insertSimple(1, 82, objDTO.getId(), 2,
                    "更新流程申请信息",
                    FastJsonUtils.toJSONString(objDTO),
                    curr_obj.getId(),
                    IpUtils.getClientIp(request),
                    SystemUtils.getBrowserInfo(request));
            //endregion

            //操作成功 结果返回
            map = OperateCode.CompositionResult(map, 1);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }
    //endregion

    //region ajax 异步获取数据（废弃）

    /**
     * 异步获取数据（废弃）
     *
     * @param request    servlet
     * @param model      model
     * @param businessid 业务Id
     * @param applytitle 标题
     * @param status     状态
     * @param applytype  1普通审批
     * @param pn         每几页
     * @param oneself    只查自己
     * @return json
     */
    @RequestMapping(value = "/getApplyListAbandon", method = RequestMethod.POST)
    public String ajaxGetApplyListAbandon(HttpServletRequest request, Model model, Integer businessid, String applytitle, Integer status, Integer applytype, Integer pn, Integer oneself) {
        businessid = (businessid == null ? 0 : businessid);
        businessid = (businessid == 0 ? -9999 : businessid);

        String pin = AdminBaseClass.getPin(request);
        AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);

        List<WorkflowApplyDTO> noneList = new ArrayList<>();
        Page<WorkflowApplyDTO> dataPage = null;

        WorkflowApplyDTOQuery query = new WorkflowApplyDTOQuery();
        query.setBusinessId(businessid);
        query.setStatus(status);
        query.setPn(pn);
        if (applytype == 1) { //普通审批
            query.setApplyType(applytype);
        }

        //正常查看
        Integer canExec = modelService.getLookAlldataAuthor(pin);
        if (oneself == 0 && canExec > 0) {
            //管理员可以看到所有流程，拥有权限的人也可以查看全部，前提是不能是“只查自己”
            query.setLikeName(applytitle.trim());
            query.setOrderBy("order by id desc");
            dataPage = applyService.getForPage(query);

        } else {
            query.setApplyLikeName(applytitle.trim());
            query.setSecondaryCurrUser(curr_obj.getId());
            query.setOrderBy("order by a.id desc");
            dataPage = applyService.getJoinSecondaryForPage(query);
        }

        // 实时更新列表信息
        if (dataPage != null && dataPage.getItems().size() > 0) {
            WorkflowBusinessDTO businessDTO;

            for (WorkflowApplyDTO item : dataPage.getItems()) {
                //审批人
                item.setApplyName(modelService.getManageName(item.getApply()));

                //审批状态
                item.setStatusName(ApplyStatusEnum.getEnumByKey(item.getStatus()));

                //流程类型
                businessDTO = businessService.getById(item.getBusinessId());
                item.setBusinessName(businessDTO == null ? "--" : businessDTO.getBusinessName());
            }
        }

        model.addAttribute("page", dataPage);
        model.addAttribute("PagePackage", PagePackage(dataPage.getPn(), dataPage.getStart(), dataPage.getPageSize(), dataPage.getTotalPages(), dataPage.getTotalItems()));

        model.addAttribute("bid", businessid);
        model.addAttribute("title", applytitle);
        model.addAttribute("applytype", applytype);
        model.addAttribute("status", status);

        return "basic/wfapply/com-content";
    }
    //endregion
}